//save,get
const express=require('express');
const router=express.Router();
const passport=require("passport");
const isExist=require('../../config/publicFun').isExist;
const Great=require('../../models/Great');


//$route  Post api/greats/doGreat
//@desc   return state
//@access private
router.post("/doGreat",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let option={
        user:req.user.id,
        post:req.body.post,
    };
    isExist(option,Great,doc=>{
        //如果不存在这个用户对这条博客的点赞记录就存一条
        if(doc.length==0){
            let great=new Great(option);
            great.save((err)=>{
                if(err){
                    res.json({"ok":1});
                }
                else{
                    res.json({"ok":0});
                }
            })
        }
        else{
            //如果存在这个用户对这条博客的点赞记录就删除
            Great.deleteOne(option,err=>{
                if(err){
                    res.json({"ok":1});
                }
                else{
                    res.json({"ok":2});
                }
            })
        }
    })
})

//$route  Post api/greats/getGreats
//@desc   return postId
//@access private
//用户点过赞的post
router.post('/getGreats',passport.authenticate("jwt",{session:false}),(req,res)=>{
    Great.find({'user':req.user.id},{'_id':0,'post':1})
    .then((docs)=>{
        
        res.json({'ok':0,'data':docs});
        
    })
})

//$route  Post api/greats/isExist
//@desc   return state
//@access private
//用户是否点过赞
router.post('/isExist',passport.authenticate("jwt",{session:false}),(req,res)=>{
    isExist({user:req.user.id,post:req.body.post},Great,(doc)=>{
        if(doc.length==0){
            res.send({'isExist':false});
        }
        else {
            res.send({'isExist':true});
        }
    })
})

module.exports=router;